package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuSaleVo;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.springframework.util.CollectionUtils;


@Service("spuService")
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    //
    @Override
    public PageResultVo querySpuByCidAndPage(PageParamVo pageParamVo, Long categoryId) {
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();

        //如果categoryId 不为0 ，需要查本类
        if (categoryId != 0) {
            wrapper.eq("category_id", categoryId);
        }

        //关键字
        String key = pageParamVo.getKey();
        if (StringUtils.isNotBlank(key)) {  //检查  是否不为空 ("")、不为空且不为空白
            //wrapper 后面直接写条件，条件之间默认是and关系，并且都没有括号

            //  select * from pms_spu where category_id=225 and (id =7 or `name` like '%7%');
            // 下面的 是 在 and 后面 加上括号 括号中间有 or
            wrapper.and(t -> t.eq("id", key).or().like("name", key));
        }


        IPage<SpuEntity> page = this.page(
                pageParamVo.getPage(),
                wrapper
        );

        return new PageResultVo(page);
    }

    @Autowired
    private SpuDescMapper spuDescMapper;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuImagesService imagesService;
    @Autowired
    private SkuAttrValueService skuAttrValueService;
    @Autowired
    private GmallSmsClient smsClient;
    @Autowired
    private SpuDescService descService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    //保存spu的大保存方法
    //抽取方法 快捷键 Alt+Shift+M
    @GlobalTransactional
    @Override
    public void bigSave(SpuVo spu) {
        //1、先保存spu 相关信息
        //1.1 保存pms_spu
        Long spuId = saveSpuInfo(spu);

        //1.2 保存pms_spu_desc
        this.descService.saveSpuDesc(spu, spuId);

        //1.3 保存pms_spu_attr_value
        saveBaseAttrs(spu, spuId);

        //2、再保存sku 相关信息
        saveSkuInfo(spu, spuId);
        //int i= 1/0;

        // 发送消息
        this.rabbitTemplate.convertAndSend("PMS_ITEM_EXCHANGE", "item.insert", spuId);

    }

    private void saveSkuInfo(SpuVo spu, Long spuId) {
        List<SkuVo> skuVos = spu.getSkus();
        if (CollectionUtils.isEmpty(skuVos)) {
            return;
        }

        skuVos.forEach(skuVo -> {//2.1 保存pms_sku
            skuVo.setSpuId(spuId);
            skuVo.setCategoryId(spu.getCategoryId());
            skuVo.setBrandId(spu.getBrandId());
            //获取页面的图片列表
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty(images)) {
                //取第一张图片作为默认图片
                skuVo.setDefaultImage(StringUtils.isNotBlank(skuVo.getDefaultImage()) ? skuVo.getDefaultImage() : images.get(0));
            }

            this.skuMapper.insert(skuVo);
            Long skuId = skuVo.getId();

            //2.2 保存pms_sku_images
            if (!CollectionUtils.isEmpty(images)) {
                this.imagesService.saveBatch(images.stream().map(image -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setUrl(image);
                    imagesEntity.setSkuId(skuId);

                    // 如果当前图片的地址和 sku的默认图片地址相同，则设置为1 否则设置为0
                    imagesEntity.setDefaultStatus(StringUtils.equals(skuVo.getDefaultImage(), image) ? 1 : 0);
                    return imagesEntity;
                }).collect(Collectors.toList()));

            }
            //2.3 保存pms_sku attr_value
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if (!CollectionUtils.isEmpty(saleAttrs)) {
                saleAttrs.forEach(skuAttrValueEntity -> skuAttrValueEntity.setSkuId(skuId));
                this.skuAttrValueService.saveBatch(saleAttrs);
            }

            //3、最后保存 营销信息
            SkuSaleVo skuSaleVo = new SkuSaleVo();
            BeanUtils.copyProperties(skuVo, skuSaleVo);
            skuSaleVo.setSkuId(skuId);
            this.smsClient.saveSales(skuSaleVo);

        });
    }

    private void saveBaseAttrs(SpuVo spu, Long spuId) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();

        List<SpuAttrValueEntity> spuAttrValueEntities = baseAttrs.stream()
//                .filter(spuAttrValueVo -> {
//                    return spuAttrValueVo.getAttrValue()!=null;
//                })
                .filter(spuAttrValueVo -> spuAttrValueVo.getAttrValue() != null)
                .map(spuAttrValueVo -> {
                    //把SpuAttrValueVo集合转化为SpuAttrValueEntity集合
                    SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                    BeanUtils.copyProperties(spuAttrValueVo, spuAttrValueEntity);
                    spuAttrValueEntity.setSpuId(spuId);
                    return spuAttrValueEntity;
                }).collect(Collectors.toList());
        //判断不为空 再进行添加
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            this.spuAttrValueService.saveBatch(spuAttrValueEntities);
        }
    }


    private Long saveSpuInfo(SpuVo spu) {
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);
        return spu.getId();
    }


//    public static void main(String[] args) {
//        List<User> users = Arrays.asList(
//                new User("hang", 11, false),
//                new User("zhou", 12, false),
//                new User("shang", 13, true),
//                new User("hai", 14, false),
//                new User("xai", 15, true)
//        );

//        //map: 把一个集合转化为另一个集合
//        users.stream().map(user -> user.getUsername()).collect(Collectors.toList()).forEach(System.out::println);
//        users.stream().map(user -> {
//            Person person = new Person();
//            person.setName(user.getUsername());
//            person.setAge(user.getAge());
//            return person;
//        }).collect(Collectors.toList()).forEach(System.out::println);
//
//        //filter: 过滤出需要的元素，组成新的集合
//        users.stream().filter(user -> {
//            return user.getAge() > 12;
//        }).collect(Collectors.toList()).forEach(System.out::println);
//
//        users.stream().filter(User::isSex).collect(Collectors.toList()).forEach(System.out::println);

    //reduce: 求和
//        Integer integer = users.stream().map(user -> user.getAge()).reduce((a, b) -> a + b).get();
//        System.out.println(integer);
//    }

}

//@Data
//@NoArgsConstructor
//@AllArgsConstructor
//class User {
//    private String username;
//    private Integer age;
//    private boolean sex;
//}
//
//@Data
//class Person {
//    private String name;
//    private Integer age;
//}
